package com.youbug.custservice.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youbug.common.constant.AgentConstant;
import com.youbug.custservice.entity.Chat;
import com.youbug.custservice.entity.ServiceTicket;
import com.youbug.custservice.service.IChatService;
import com.youbug.custservice.service.IQueueService;
import com.youbug.custservice.service.IServiceTicketService;
import com.youbug.custservice.vo.ChatVo;
import com.youbug.common.vo.R;
import com.youbug.custservice.websocket.ChatsInfoHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 服务单表 前端控制器
 * </p>
 *
 * @author youbug
 * @since 2023-01-08
 */
@RestController
@RequestMapping("/online")
public class OnlineController {

    @Autowired
    private IQueueService queueService;
    @Autowired
    private IServiceTicketService serviceTicketService;
    @Autowired
    private IChatService chatService;

    @GetMapping("/getServiceTicket/{id}")
    public R<ServiceTicket> getUser(@PathVariable Long id){

        ServiceTicket ticket = serviceTicketService.getById(id);

        return R.ok(ticket);
    }
    @PostMapping("/getHisChats")
    public R<IPage<Chat>> getChats(@RequestBody ChatVo chatVo){

        IPage<Chat> chats = chatService.getChatPageForClient(chatVo);

        return R.ok(chats);
    }

    @PostMapping("/addTicket")
    public R<ServiceTicket> add(@RequestBody ServiceTicket ticket){

        boolean save = serviceTicketService.save(ticket);

        return  R.ok(ticket);
    }

    @PostMapping("/updateTicket")
    public R<Boolean> update(@RequestBody ServiceTicket ticket){

        boolean save = serviceTicketService.updateById(ticket);

        return  R.ok(save);
    }

    @GetMapping("/signIn/{agentId}")
    public R<Boolean> signIn(@PathVariable Long agentId){
        ChatsInfoHolder.agentSessionInfoMap.get(agentId).setState(AgentConstant.SINGIN.getCode());
        return  R.ok(true);
    }
    @GetMapping("/signOut/{agentId}")
    public R<Boolean> signOut(@PathVariable Long agentId){
        ChatsInfoHolder.agentSessionInfoMap.get(agentId).setState(AgentConstant.SIGNOUT.getCode());
        return  R.ok(true);
    }

    @GetMapping("/ready/{agentId}")
    public R<Boolean> ready(@PathVariable Long agentId){
        ChatsInfoHolder.agentSessionInfoMap.get(agentId).setState(AgentConstant.READY.getCode());
         queueService.restartDistribute();

        return  R.ok(true);
    }

    @GetMapping("/rest/{agentId}")
    public R<Boolean> rest(@PathVariable Long agentId){
        ChatsInfoHolder.agentSessionInfoMap.get(agentId).setState(AgentConstant.REST.getCode());
        return  R.ok(true);
    }

    @PostMapping("/reverseRecord")
    public R<String> uploadFile(MultipartFile file){

        String fileUrl = chatService.saveAndReverseRecord(file);

        return R.ok(fileUrl);
    }

}

